package com.zpark.blog.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false); // 获取当前会话，不创建新会话

        // 检查用户是否登录
        boolean isLoggedIn = (session != null && session.getAttribute("isLoggedIn") != null
                && Boolean.TRUE.equals(session.getAttribute("isLoggedIn")));
        if (isLoggedIn) {
            // 用户已登录，重定向到写博客页面
            response.sendRedirect(request.getContextPath() + "/edit-article.jsp");
        } else {
            // 用户未登录，重定向到登录页面，并设置目标地址为写博客页面
            response.sendRedirect(request.getContextPath() + "/login.jsp?target=/edit-article.jsp");
            // 处理POST请求，这里可以是提交博客内容等操作
            doGet(request, response);
        }

    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 模拟博客列表数据
        List<Blog> blogs = new ArrayList<>();
        blogs.add(new Blog(1, "我的第一篇博客", "2024-12-17", "关注Gxd_01c,一起学编程! Lorem ipsum dolor sit amet consectetur..."));
        blogs.add(new Blog(2, "我的第二篇博客", "2024-12-17", "这里应该是第二篇博客的摘要。"));

        // 将博客列表数据存储在请求属性中
        request.setAttribute("blogs", blogs);

        // 转发到 view-articles.jsp 页面
        request.getRequestDispatcher("/webapp/view-articles.jsp").forward(request, response);

    }

    // 内部类表示博客对象
    private static class Blog {
        private int id;
        private String title;
        private String date;
        private String abstractText;

        public Blog(int id, String title, String date, String abstractText) {
            this.id = id;
            this.title = title;
            this.date = date;
            this.abstractText = abstractText;
        }

        public int getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        public String getDate() {
            return date;
        }

        public String getAbstractText() {
            return abstractText;
        }
    }
}
